package com.zyfu.demo.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zyfu.demo.domain.District;
import com.zyfu.demo.constant.DistrictLevel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * <b>高德，json数据解析</b>
 * <pre>
 * 描述<br/>
 * 作用：；<br/>
 * 限制：；<br/>
 * </pre>
 *
 * @author 张永福
 * @since  2024/2/26 13:29
 */
public class GaoDeJsonParser {

    public static void main(String[] args) throws IOException {
//        List<District> parse = parse("E:\\workSpace\\china-districts-demo\\src\\main\\data\\安徽省.json");
        List<District> parse = parse("E:\\workSpace\\china-districts-demo\\src\\main\\data\\全国.json");
        JSONConfig jsonConfig = new JSONConfig();
        JSONUtil.toJsonStr(parse, jsonConfig);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                District.class, parse);
        String dest = "E:\\workSpace\\china-districts-demo\\src\\main\\data-result\\全国.xlsx";
        try (FileOutputStream fis = new FileOutputStream(dest)){
            workbook.write(fis);
        }
        workbook.close();
    }

    public static List<District> parse(String filePath) {
        List<District> result = new ArrayList<>();
        JSONConfig jsonConfig = new JSONConfig();
        jsonConfig.setIgnoreCase(true);
        String content = FileUtil.readString(filePath, Charset.defaultCharset());
        JSONObject entries = JSONUtil.parseObj(content, jsonConfig);
        JSONArray districts = entries.getJSONArray("districts");
        JSONObject jsonObject = districts.getJSONObject(0);
        District bean = jsonObject.toBean(District.class);
        bean.setParentAdCode("100000");
        result.add(bean);
        setParent(bean, result);
        return result;
    }

    private static void setParent(District district, List<District> result) {
        List<District> districts = district.getDistricts();
        DistrictLevel level = DistrictLevel.parse(district.getLevel());
        district.setLevelName(level.getName());
        district.setLevelNo(level.getLevelNum());
        if (CollectionUtils.isNotEmpty(districts)) {
            result.addAll(districts);
            districts.forEach(dis -> {
                dis.setParentAdCode(district.getAdCode());
                setParent(dis, result);
            });
        }
    }


}
